package service.impl;

import Dao.AdminDao;
import Dao.BaseDao;
import Dao.UserDao;
import Dao.impl.AdminDaoImpl;
import Dao.impl.BaseDaoImpl;
import Dao.impl.UserDaoImpl;
import entity.Orders;
import entity.Seat;
import entity.Train;
import entity.User;
import service.AdminService;
import service.BaseService;
import untils.Msg;
import untils.SqlCollection;

import javax.xml.crypto.Data;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;

public class AdminServiceImpl extends BaseServiceImpl implements AdminService {
    private AdminDao adminDao = new AdminDaoImpl();

    private BaseDao baseDao = new BaseDaoImpl();

    private UserDao userDao = new UserDaoImpl();

    private SqlCollection sqlCollection = new SqlCollection();
    @Override
    public Msg<ArrayList<User>> findAllUserData() {
        return adminDao.findAllUserData();
    }

    @Override
    public Msg deleteUserData(int id) {

        return adminDao.deleteUserData(id);
    }

    @Override
    public Msg<User> addUserData(User user1) {
        Msg<User> msg = new Msg<>();
        try{
            sqlCollection.beginTransaction();
            //1.判断添加用户是否已经注册 :电话号码信息
            int flag = baseDao.findUserByPhone(user1.getPhone());

            if(flag>0){
                System.out.println("您输入的账号已经被注册，请你检查相关信息");
            }else {
                msg = adminDao.addUserData(user1);
            }
            //成功：事务提交
            sqlCollection.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlCollection.rollback();
        }finally {
            sqlCollection.closeConnection();
        }
        //开启事务
        return msg;
    }

    @Override
    public Msg updateTrainsDao(Train train) {
        return adminDao.updateTrainsDao(train);
    }

    @Override
    public Msg<Seat> updateSeatData(String type,Seat seat) {
        return adminDao.updateSeatData(type,seat);
    }

    @Override
    public Msg<ArrayList<User>> findAllAdminData() {
        return adminDao.findAllAdminData();
    }

    @Override
    public int findUserByPhone(String phone) {
        return adminDao.findUserByPhone(phone);
    }

    @Override
    public void addAdminData(int userId) {
        adminDao.addAdminData(userId);
    }

    @Override
    public void deleteAdminData(int userId) {
        adminDao.deleteAdminData(userId);
    }

    @Override
    public void importOrdersList() {
        //1、调用dao层中查询所有学生列表的方法--之前的方法 参数:无   返回值： ArrayList<StudentEntity>
        ArrayList<Orders> orders =  adminDao.findAllOrderData();

        BufferedWriter bw =null;
        try {
            //2、创建字符输出流对象 BufferedWriter
            bw  = new BufferedWriter(new FileWriter("file\\OrderInfo.doc"));
            //3、遍历集合数据
            for (Orders order : orders) {
                StringBuffer sbf = new StringBuffer();
                //4、处理当前数据的格式(拼接对象中的数据成字符串，以空格分隔)
                sbf.append(order.getOrderId()+"   ")
                        .append(order.getTicketId()+"   ")
                        .append(order.getUserId()+"   ")
                        .append(order.getTrain_id()+"    ")
                        .append(order.getTotalPrice()+"    ")
                        .append(order.getOrderTime()+"  ")
                        .append(order.getStatus()+"     ")
                        .append(order.getTicket()+"     ")
                        .append(order.getTrain()+"      ");
                //5、一行一行的写数据到指定文件中
                bw.write(sbf.toString());
                bw.newLine();
            }
            //6、刷新
            bw.flush();
            //8、返回值
            Msg.msg = "导出成功";
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //7、关闭资源
            try {
                if (bw!=null){
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void importTrainList() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入附件文件路径:");
        String path = sc.next();
        //3、调用service中导入信息的方法 参数：路径 adminId   返回值：boolean
        importTrainList(path);
        System.out.println("请输入附件文件路径:");
        String path2 = sc.next();
        importSeatList(path2);
    }

    @Override
    public void importTrainList(String path) {
        BufferedReader br = null;
        try {
            //1、创建字符输入流对象 BufferedReader
            br = new  BufferedReader(new FileReader(path));
            //2、循环读取数据  readLine() ，一行一行的读数据
            Train train = null;
            String line = null;
            while((line=br.readLine())!=null){
                //3、每读一行，创建一个CourserEntity对象
                String[] ary = line.split(",");
                Date date1 = StringToDate(ary[2]);
                Date date2 = StringToDate(ary[3]);
                train = new Train(Integer.valueOf(ary[0]) ,ary[1], new java.sql.Date(date1.getTime()), new java.sql.Date(date2.getTime()), ary[4], ary[5]);
                //4、调用dao层插入课程信息的方法 参数：CourserEntity  返回值：无
                adminDao.addTrain(train);
                adminDao.addTrainName(train.getTrainName());
            }
            //6、返回值
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5、关闭资源
            try {
                if (br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //6、返回值
    }

    @Override
    public void importSeatList(String path) {
        BufferedReader br = null;
        try {
            //1、创建字符输入流对象 BufferedReader
            br = new  BufferedReader(new FileReader(path));
            //2、循环读取数据  readLine() ，一行一行的读数据
            Seat seat = null;
            String line = null;
            while((line=br.readLine())!=null){
                //3、每读一行，创建一个CourserEntity对象
                String[] ary = line.split(",");
                seat = new Seat(Integer.valueOf(ary[0]),ary[1],ary[2],Integer.valueOf(ary[3])
                        ,Integer.valueOf(ary[4]));
                //4、调用dao层插入课程信息的方法 参数：CourserEntity  返回值：无
                adminDao.addSeat(seat);
            }
            //6、返回值
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //5、关闭资源
            try {
                if (br!=null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //6、返回值
    }

    public Date StringToDate(String s){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            // 使用parse方法将字符串解析为Date对象
            date = sdf.parse(s);
        } catch (ParseException e) {
            // 如果字符串格式不正确，将抛出ParseException
            e.printStackTrace();
            // 在这里处理错误，比如使用默认日期时间或通知用户检查输入
        }
        return date;
    }

}
